<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
import { useUserStore } from '@/stores/user'
import { baseURL } from '@/utils/request';
import { io, type Socket } from '@hyoga/uni-socket.io'
import RoomStatus from './components/room-status.vue';
import { getPatientConsultOrderDetailAPI } from '@/apis/consult';
import { OrderStatus, type GetPatientConsultOrderDetailData } from '@/types/consult';
import { nextTick, ref } from 'vue';
import type { ChatMsgListData, MsgItem } from '@/types/room';
import PatientInfo from './components/patient-info.vue';
import NotifyInfo from './components/notify-info.vue';
import MessageInfo from './components/message-info.vue';
import PrescriptionInfo from './components/prescription-info.vue';
import RateInfo from './components/rate-info.vue';
import { postUploadFileAPI } from '@/apis/common';
const store = useUserStore()
const props = defineProps<{
  payResult:'true' | 'false'
  orderId: string
  type:string
}>()
// 创建socket连接
const socket = io(baseURL,{
  auth:{token:`Bearer ${store.token}`},
  query:{orderId:props.orderId},
  // 支持 websocket 和 轮询 两种传输方式
  transports: ['websocket','polling'],
  // 超时时间
  timeout: 5000,
})

// 问诊订单状态
const orderDetail = ref<GetPatientConsultOrderDetailData>()
const getOrderDetail = async () => {
  const res = await getPatientConsultOrderDetailAPI(props.orderId)
  // console.log(res)
  orderDetail.value = res.data
}
getOrderDetail()
// 监听后端自定义事件
socket.on('statusChange',(data)=>{
  console.log(data)
  getOrderDetail()
})

// 定义数组 接收消息
const msgList = ref<MsgItem[]>([])
// 历史消息 事件名为chatMsgList
socket.on('chatMsgList',(res:ChatMsgListData)=>{
  // 判断业务状态码
  if(res.code !== 10000) return
  // 循环消息组（按时间节点划分，一个消息组包含多条消息）
  res.data?.forEach((item)=>{
    // 如果有消息列表
    if(item.items){
      // 将消息组中的消息追加到消息列表中
      msgList.value.push(
        {
        msgType:31,
        createTime:item.createTime,
        msg:{
          content:item.createTime
        },
      },...item.items)
    }
  })
  // console.log(msgList.value);
  
})
const scrollIntoViewId = ref('')
// 接受回复消息
socket.on('receiveChatMsg', async (res:MsgItem)=>{
  // 修改消息为已读
  socket.emit('updateMsgStatus', res.id)
    // 接收到的消息追加到消息列表中
    msgList.value.push(res)
    // console.log('接受回复消息',res);
    // 通过nextTick 等待消息列表更新
    await nextTick()
    // 接收消息后，滚动到最新消息
    scrollIntoViewId.value = `id-${res.id}`
})
socket.on('connect',()=>{
  console.log('socket连接成功')
})
socket.on('disconnect',()=>{
  console.log('连接失败')
})
// 用户发送消息
const textMessage = ref('')
const sendMessage = ()=>{
  if(!textMessage.value.trim()){
    uni.showToast({title:'请输入消息',icon:'none'})
    return
  }
  // console.log(store.userInfo);
  
  // 发送消息给服务器
  socket.emit('sendChatMsg',{
    from:store.userInfo?.id,//发送人用户的id
    to:orderDetail.value?.docInfo?.id,//接收人医生的id
    msgType:1,
    msg:{
      content:textMessage.value
    }
  })
  // 清空输入框
  textMessage.value = ''
}
// 上传图片
const handleUploadImage = async () => {
  // 非咨询中状态，不能发送图片消息
  if (orderDetail.value?.status !== OrderStatus.ZiXunZhong) {
    uni.showToast({ title: '当前状态不能发送图片消息', icon: 'none' })
    return
  }

  // 选择图片（支持相册和相机）
  const { tempFilePaths } = await uni.chooseImage({
    count: 1, // 最多可以选择的图片张数
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
  })

  // 上传图片，传递图片路径
  const res = await postUploadFileAPI(tempFilePaths[0])
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id, // 发送人id
    to: orderDetail.value?.docInfo?.id, // 接收人id (医生id)
    msgType: 4, // 消息类型，4 表示图片消息
    msg: {
      picture: res.data,
    },
  })
}

</script>

<template>
  <view class="room-page">
     <!-- 咨询室状态组件 -->
     <RoomStatus 
     v-if="orderDetail"
     :status="orderDetail?.status" 
     :statusValue="orderDetail?.statusValue" 
     :countdown="orderDetail?.countdown" />
    <!-- 消息列表 -->
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
      :scroll-into-view="scrollIntoViewId"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
         <view v-for="item in msgList" :key="item.id" :id="`id-${item.id}`" >
          {{ item.msgType }}
          <PatientInfo 
          v-if="item.msgType === 21"
          :info="item.msg?.consultRecord!"
          />
          <NotifyInfo v-else-if="item.msgType&&item.msgType>=31" :type="item.msgType">
            {{ item.msg?.content }}
          </NotifyInfo>
          <!-- 文字图片消息 -->
          <MessageInfo 
          v-else-if="item.msgType === 1 || item.msgType === 4"
          :info="item"
          ></MessageInfo>
          <!-- 处方 -->
          <PrescriptionInfo v-else-if="item.msgType === 22" :info="item.msg?.prescription!"></PrescriptionInfo>
          <!-- 医生评价 -->
           <RateInfo 
           v-else-if="item.msgType === 23"
           :orderId="props.orderId"
           :doctorId="orderDetail?.docInfo?.id"
           ></RateInfo>
           <!-- 已经评价 -->
           <RateInfo
            :evaluateDoc="item.msg?.evaluateDoc"
            has-evaluate?
            v-if="item.msgType === 24"
          />
         </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          v-model="textMessage"
          @confirm="sendMessage"
          :disabled="orderDetail?.status !== OrderStatus.ZiXunZhong"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button" @click="handleUploadImage">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  @import './index.scss';
</style>